<template>
  <!-- 歌曲详情页 -->
  <div class="box">
    <div class="content" v-if="data !== null">
      <div class="play">
        <el-image :src="require('../assets/image/player_bar.png')" :class="play === true ? 'playBar' : 'playBarP'">
        </el-image>
        <div :class="play === true ? 'discR' : 'disc'">
          <!-- 左歌曲图片 -->
          <el-image :src="image" lazy />
        </div>
      </div>

      <!-- 中间 -->
      <div class="centent">
        <div class="name">{{ data[0].name }}
          <div v-if="data[0].mv !== 0" class="mv" @click="playMv(data[0])">
            MV
          </div>
        </div>
        <div class="desc">
          <div class="alName" @click="getAlb(data[0].al.id)">
            {{ data[0].al.name }}
          </div>
          <div v-for="item in data[0].ar" :key="item.id" class="arName" @click="getArt(item)">
            {{ item.name }}
          </div>
        </div>

        <!-- 歌词 -->
        <div class="lyric" ref="lyric">
          <div v-for="(item, key, index) in lyricArr" :key="key" class="lyricArr"
            :style="index === lyricIndex ? 'color:red;font-size:24px' : 'color:black'" @click="position(key)">
            <div>
              <div style="
                  width: 100%;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                ">
                {{ item }}
              </div>
              <!-- 译文 -->
              <div v-if="tlyricArr !== null">{{ tlyricArr[key] }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 相似推荐 -->
      <div class="right">
        <div class="title">相似音乐</div>

        <div class="simiBox">
          <div v-for="item in simiData" :key="item.id" class="simiItem">
            <el-image :src="item.al.blurPicUrl" fit="cover" @click="playSimi(item)" lazy>
              <div slot="placeholder" class="image-slot">
                <el-image :src="require('../assets/image/hot50.jpg')" fit="cover" @click="playSimi(item)" lazy>
                </el-image>
              </div>
            </el-image>
            <div class="textBox">
              <!-- 歌曲名称 -->
              <div>{{ item.name }}</div>
              <!-- 作者名称 -->
              <div>
                <div v-for="item in item.ar" :key="item.id">
                  {{ item.name }}
                </div>
              </div>
              <!-- 专辑名称 -->
              <div>
                <div>{{ item.al.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Comment />

    <div class="loading" v-if="show === true">
      <i class="el-icon-loading"></i>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  components: {
    Comment: () => import('./songComment.vue'),
  },
  computed: {
    ...mapState(['nowPlaySong', 'nowID', 'pause', 'playTime']),
  },
  mounted() {
    this.ids = this.nowPlaySong.songId;
    this.getData(this.ids);
    this.lyric(this.ids);
    this.image = this.nowPlaySong.pic;
    this.play = this.pause.pause;
    this.time = this.playTime.playTime;
    this.simi(this.ids);
  },
  watch: {
    nowPlaySong(newVal, oldVal) {
      this.getData(newVal.songId);
      this.image = newVal.pic;
      this.lyric(newVal.songId);
      this.simi(newVal.songId);
      this.scrollTop = 0;
      this.$refs.lyric.scrollTop = this.scrollTop;
    },
    pause(newVal, oldVal) {
      this.play = newVal.pause;
    },
    playTime(newVal, oldVal) {
      this.time = newVal.playTime;
      let i = 0;
      for (const key in this.lyricArr) {
        if (+key == this.time) {
          this.lyricIndex = i;
          {
            if (i > 5) {
              if (this.tlyricArr !== null) {
                this.scrollTop = 80 * (i - 5);
                this.$refs.lyric.scrollTop = this.scrollTop;
              } else {
                this.scrollTop = 55 * (i - 5);
                this.$refs.lyric.scrollTop = this.scrollTop;
              }
            }
          }
        }
        i++;
      }
    },
  },
  data() {
    return {
      data: null,
      ids: null,
      image: null,
      play: true,
      lyricData: null,
      lyricArr: null,
      tlyricArr: null,
      time: null,
      lyricIndex: null,
      scrollTop: 0,
      show: false,
      simiData: null,
      simiImg: '',
    };
  },
  methods: {
    ...mapActions([
      'savePlayTime',
      'saveAlbumData',
      'saveOpenItem',
      'saveNowSongCount',
      'saveNowSong',
      'clickPlay',
      'saveMVurl',
      'saveResMv',
      'saveMvBes',
      'saveArtistsItem',
      'saveNowRow',
    ]),
    // 获取歌曲详情
    async getData(e) {
      this.data = null;
      this.$api.musicItem({ ids: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.data = ret.songs;
      });
    },
    // 获取歌词
    async lyric(e) {
      this.lyricData = null;
      this.lyricArr = null;
      this.tlyricArr = null;
      this.$api.lyric({ id: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.lyricData = ret;
        this.lyricArr = ret.lrc.lyric.split('[').slice(1);
        this.lyricArr = this.toArr(this.lyricArr);
        if (ret.tlyric.lyric !== '') {
          this.tlyricArr = ret.tlyric.lyric.split('[').slice(1);
          this.tlyricArr = this.toArr(this.tlyricArr);
        }
      });
    },

    // 歌词转数组的处理
    toArr(e) {
      const lrcObj = {};
      e.forEach((item) => {
        const arr = item.split(']'); // 再分割右括号
        // 时间换算成秒
        const m = parseInt(arr[0].split(':')[0]);
        const s = parseInt(arr[0].split(':')[1]);
        arr[0] = m * 60 + s;
        if (arr[1] != '\n') {
          // 去除歌词中的换行符
          lrcObj[arr[0]] = arr[1];
        }
      });
      return lrcObj;
    },

    // 定位到指定位置
    position(key) {
      document.getElementById('playMusicAudio').currentTime = key;
    },

    // 跳转到专辑页面
    getAlb(e) {
      this.show = true;
      this.$api.album({ id: e, timestamp: this.$utils.timestamp(), cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveAlbumData({ albumData: ret });
        window.sessionStorage.setItem('album', e);
        document.querySelector('.header').style.background = '#ec4141';
        this.$router.push(`/albumPage?id=${e}`);
        this.saveOpenItem({ openItem: false });
        this.show = false;
      });
    },

    // 跳转到歌手页面
    async getArt(e) {
      this.show = true;
      window.sessionStorage.setItem('artists', e.id);
      document.querySelector('.header').style.background = '#ec4141';
      this.$router.push(`/artistsPage?id=${e.id}`);
      await this.saveOpenItem({ openItem: false });
      this.show = false;
    },

    // 获取相似音乐
    simi(e) {
      this.simiData = null;
      this.$api.simiSong({ id: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.simiData = ret.songs;
        for (const song of this.simiData) {
          // 某些键值和之前请求的不符合，进行修改
          song.al = song.album;
          delete song.album;
          song.alia = song.alias;
          delete song.alias;
          song.ar = song.artists;
          delete song.artists;
          song.dt = song.duration;
          delete song.duration;
        }
      });
    },

    // 播放相似歌曲
    async playSimi(e) {
      // 需要存入当前播放的歌曲
      await this.saveNowSongCount({ nowSongCount: this.simiData });
      const cookie = localStorage.getItem('cookie');
      this.$api.songUrl({ cookie, id: e.id, timestamp: this.$utils.timestamp() }).then((ret) => {
        const title = e.name;
        const arr = e.ar.map((item1) => {
          return item1.name;
        });
        const artist = arr.join();
        const pic = e.al.picUrl;
        if (ret.data[0].url !== null) {
          this.saveNowSong({
            id: 0,
            title,
            artist,
            src: ret.data[0].url,
            pic,
            songId: ret.data[0].id,
          });
          this.$api.scrobble({ id: e.id, cookie: cookie, sourceid: e.al.id, timestamp: this.$utils.timestamp() })
          this.clickPlay({ ifPlay: false });
        } else {
          this.$message.error('该歌曲暂时无法播放!!!');
        }
      });
    },

    // 点击播放MV
    playMv(e) {
      // 获取到MV的地址
      this.$api.mvUrl({ id: parseInt(e.mv), cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveMVurl({ mvUrl: ret.data.url });
      });
      this.getArtists(e.ar[0].id);
      this.getResMv(e.mv);
      this.getItem(e.mv);
    },

    // 获取相似MV
    getResMv(e) {
      this.$api.simiMv({ mvid: e, timestamp: this.$utils.timestamp(), cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveResMv({ resMv: ret });
      });
    },

    // 获取MV基础信息
    getItem(e) {
      this.loading = true;
      this.$api.mvDetail({ mvid: e, timestamp: this.$utils.timestamp(), cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveMvBes({ mvBes: ret });
        document.querySelector('.header').style.background = '#ec4141';
        this.$router.push(`/mvPlay?id=${e}`);
        this.saveOpenItem({ openItem: false });
        this.show = false;
      });
    },

    // 获取MV作者
    getArtists(e) {
      window.sessionStorage.setItem('artists', e);
      this.$api.arDetail({ id: e, cookie: localStorage.getItem('cookie') }).then((ret) => {
        this.saveArtistsItem({ artistsItem: ret.data });
      });
    },
  },
};
</script>

<style scoped>
.box {
  background: linear-gradient(to bottom, #808080, #ffffff);
  width: 100%;
  overflow: scroll;
  height: calc(100vh);
}

.disc,
.discR {
  width: 350px;
  height: 350px;
  background: url("../assets/image/disc.png");
  background-size: contain;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 150px;
}

.play {
  position: relative;
}

.playBar,
.playBarP {
  width: 100px;
  position: absolute;
  z-index: 10;
  left: 130px;
  top: 50px;
}

.playBar {
  transform-origin: left top;
  transform: rotate(0deg);
  animation: play .5s linear;
}

.playBarP {
  transform-origin: left top;
  transform: rotate(-20deg);
  animation: stop .5s linear;
}


.discR {
  animation: rotate 5s linear infinite;
}

.disc .el-image,
.discR .el-image {
  width: 250px;
  height: 250px;
  border-radius: 50%;
  overflow: hidden;
}

.alName {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(359deg);
  }
}

@keyframes stop {
  from {
    transform: rotate(0deg)
  }

  to {
    transform: rotate(-20deg)
  }
}

@keyframes play {
  from {
    transform: rotate(-20deg)
  }

  to {
    transform: rotate(0deg)
  }
}

.content {
  display: flex;
  justify-content: space-around;
  z-index: 20;
}

.centent {
  width: 35%;
  display: flex;
  flex-direction: column;
  align-items: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.right {
  width: 25%;
  margin-top: 20px;
}

.name {
  font-size: 40px;
  margin-top: 20px;
  width: 100%;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  justify-content: center;
  align-items: baseline;
}

.desc {
  margin-top: 20px;
  display: flex;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  text-align: center;
  flex-direction: column;
}

.lyric {
  height: 500px;
  overflow-x: scroll;
  width: 100%;
  text-align: center;
  margin-top: 40px;
}

::-webkit-scrollbar {
  display: none;
}

.lyricArr {
  margin-bottom: 30px;
  font-size: 20px;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-icon-loading {
  position: fixed;
  font-size: 50px;
  left: 50%;
  top: 50%;
  color: #ec4141;
}

.more {
  cursor: pointer;
  text-align: center;
}

.simiBox {
  display: flex;
  flex-direction: column;
}

.simiItem {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
}

.simiItem .el-image {
  width: 100px;
  height: 100px;
  border-radius: 5px;
}

.textBox {
  width: 200px;
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  justify-content: flex-end;
}

.title {
  margin-bottom: 10px;
  font-size: 20px;
}

.mv {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 27px;
  height: 15px;
  border: 1px solid #ec4141;
  color: #ec4141;
  border-radius: 2px;
  font-size: 10px;
  margin-left: 10px;
}
</style>
